﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;

namespace ExeCMD
{
    class Program
    {
        static string programName = "cmd.exe";
        static Process p = new Process();

        static void Main(string[] args)
        {
            string[] cmd = new string[] { "ping 192.168.1.246"};
            string rstStr = ExeCmd(programName,cmd);
            Console.WriteLine("第一次返回：" + rstStr);
            string[] cmd2 = new string[] { "ping 192.168.1.19"};
            rstStr = ExeCmd(programName, cmd2);
            Console.WriteLine("第二次返回：" + rstStr);
            CloseProcess(programName);

            Console.ReadKey();
        }

        public static string ExeCmd(string procName,string[] cmd)
        {
            p.StartInfo.FileName = procName;
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.CreateNoWindow = true;
            p.Start();
            p.StandardInput.AutoFlush = true;
            for (int i=0;i < cmd.Length; i++)
            {
                p.StandardInput.WriteLine(cmd[i].ToString());
            }
            p.StandardInput.WriteLine("exit");
            string strRst = p.StandardOutput.ReadToEnd();
            p.WaitForExit();
            p.Close();
            return strRst;
        }

        public static bool CloseProcess(string procName)
        {
            bool result = false;
            System.Collections.ArrayList procList = new System.Collections.ArrayList();
            string tempName = "";
            int begpos;
            int endpos;
            foreach(System.Diagnostics.Process thisProc in System.Diagnostics.Process.GetProcesses())
            {
                tempName = thisProc.ToString();
                begpos = tempName.IndexOf("(") + 1;
                endpos = tempName.IndexOf(")");
                tempName = tempName.Substring(begpos, endpos - begpos);
                procList.Add(tempName);
                if(tempName == procName)
                {
                    if (!thisProc.CloseMainWindow()) thisProc.Kill();
                    result = true;
                }
            }
            return result;
        }
    }
}
